package cn.caskm.souvenirshopsystem.service.impl;

import cn.caskm.souvenirshopsystem.constants.BizConstants;
import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.domain.dto.PageDTO;
import cn.caskm.souvenirshopsystem.domain.po.InstantMessage;
import cn.caskm.souvenirshopsystem.domain.po.StudentUser;
import cn.caskm.souvenirshopsystem.domain.query.InstantMessageQuery;
import cn.caskm.souvenirshopsystem.domain.vo.InstantMessageVO;
import cn.caskm.souvenirshopsystem.exceptions.BizException;
import cn.caskm.souvenirshopsystem.mapper.InstantMessageMapper;
import cn.caskm.souvenirshopsystem.service.InstantMessageService;
import cn.caskm.souvenirshopsystem.service.StudentUserService;
import cn.caskm.souvenirshopsystem.utils.UserContext;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class InstantMessageServiceImpl extends ServiceImpl<InstantMessageMapper, InstantMessage> implements InstantMessageService {

    private final StudentUserService studentUserService;

    @Override
    public Result<Void> sendMessage(InstantMessage message) {
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new BizException("用户未登录");
        }

        message.setSenderId(userId.intValue());
        message.setCreateTime(LocalDateTime.now());
        message.setStatus("0"); // 未读
        message.setIsDeleted("0"); // 未删除

        save(message);
        return Result.success();
    }

    @Override
    public Result<PageDTO<InstantMessageVO>> getChatHistory(Integer senderId, Integer receiverId, Long pageNum, Long pageSize) {
        if (pageNum == null) {
            pageNum = BizConstants.DEFAULT_PAGE_NUM;
        }
        if (pageSize == null) {
            pageSize = BizConstants.DEFAULT_PAGE_SIZE;
        }

        // 查询两人之间的聊天记录
        Page<InstantMessage> page = lambdaQuery()
                .and(wrapper -> wrapper
                        .and(w -> w.eq(InstantMessage::getSenderId, senderId).eq(InstantMessage::getReceiverId, receiverId))
                        .or(w -> w.eq(InstantMessage::getSenderId, receiverId).eq(InstantMessage::getReceiverId, senderId))
                )
                .eq(InstantMessage::getIsDeleted, "0")
                .orderByAsc(InstantMessage::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        List<InstantMessage> messages = page.getRecords();
        if (CollUtil.isEmpty(messages)) {
            return Result.success(PageDTO.empty());
        }

        // 获取用户信息
        Set<Integer> userIds = new HashSet<>();
        userIds.add(senderId);
        userIds.add(receiverId);
        
        Map<Integer, StudentUser> userMap = Collections.emptyMap();
        if (CollUtil.isNotEmpty(userIds)) {
            List<StudentUser> users = studentUserService.lambdaQuery()
                    .in(StudentUser::getId, userIds)
                    .list();
            if (CollUtil.isNotEmpty(users)) {
                userMap = users.stream().collect(Collectors.toMap(StudentUser::getId, u -> u));
            }
        }

        // 组装VO
        List<InstantMessageVO> result = new ArrayList<>(messages.size());
        for (InstantMessage message : messages) {
            InstantMessageVO vo = BeanUtil.copyProperties(message, InstantMessageVO.class);
            
            StudentUser sender = userMap.get(message.getSenderId());
            if (sender != null) {
                vo.setSenderName(sender.getName());
                vo.setSenderAvatar(sender.getAvatar());
            }
            
            StudentUser receiver = userMap.get(message.getReceiverId());
            if (receiver != null) {
                vo.setReceiverName(receiver.getName());
                vo.setReceiverAvatar(receiver.getAvatar());
            }
            
            result.add(vo);
        }

        return Result.success(PageDTO.of(result, page.getPages(), page.getTotal()));
    }

    @Override
    public Result<Void> markAsRead(Long messageId) {
        InstantMessage message = getById(messageId);
        if (message == null) {
            throw new BizException("消息不存在");
        }

        message.setStatus("1"); // 已读
        message.setReadTime(LocalDateTime.now());
        updateById(message);
        
        return Result.success();
    }

    @Override
    public Result<Long> getUnreadCount(Integer userId) {
        Long count = lambdaQuery()
                .eq(InstantMessage::getReceiverId, userId)
                .eq(InstantMessage::getStatus, "0")
                .eq(InstantMessage::getIsDeleted, "0")
                .count();
        return Result.success(count);
    }

    @Override
    public Result<List<InstantMessageVO>> getRecentChats(Integer userId) {
        // 查询最近的聊天记录（简化实现）
        LambdaQueryWrapper<InstantMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w -> w.eq(InstantMessage::getSenderId, userId).or().eq(InstantMessage::getReceiverId, userId))
                .eq(InstantMessage::getIsDeleted, "0")
                .orderByDesc(InstantMessage::getCreateTime)
                .last("LIMIT 50"); // 最近50条

        List<InstantMessage> messages = list(wrapper);
        if (CollUtil.isEmpty(messages)) {
            return Result.success(Collections.emptyList());
        }

        // 获取涉及的用户信息
        Set<Integer> userIds = new HashSet<>();
        for (InstantMessage message : messages) {
            userIds.add(message.getSenderId());
            userIds.add(message.getReceiverId());
        }
        
        Map<Integer, StudentUser> userMap = Collections.emptyMap();
        if (CollUtil.isNotEmpty(userIds)) {
            List<StudentUser> users = studentUserService.lambdaQuery()
                    .in(StudentUser::getId, userIds)
                    .list();
            if (CollUtil.isNotEmpty(users)) {
                userMap = users.stream().collect(Collectors.toMap(StudentUser::getId, u -> u));
            }
        }

        // 组装VO
        List<InstantMessageVO> result = new ArrayList<>();
        for (InstantMessage message : messages) {
            InstantMessageVO vo = BeanUtil.copyProperties(message, InstantMessageVO.class);
            
            StudentUser sender = userMap.get(message.getSenderId());
            if (sender != null) {
                vo.setSenderName(sender.getName());
                vo.setSenderAvatar(sender.getAvatar());
            }
            
            StudentUser receiver = userMap.get(message.getReceiverId());
            if (receiver != null) {
                vo.setReceiverName(receiver.getName());
                vo.setReceiverAvatar(receiver.getAvatar());
            }
            
            result.add(vo);
        }

        return Result.success(result);
    }

    @Override
    public Result<Void> deleteMessage(Long messageId) {
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new BizException("用户未登录");
        }

        InstantMessage message = getById(messageId);
        if (message == null) {
            throw new BizException("消息不存在");
        }

        // 只能删除自己发送的消息
        if (!message.getSenderId().equals(userId.intValue())) {
            throw new BizException("无权删除他人消息");
        }

        message.setIsDeleted("1");
        updateById(message);
        
        return Result.success();
    }
}
